package com.corner.ui.base;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.corner.R;
import com.corner.app.App;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.base.BaseView;
import com.corner.utils.AppManager;
import com.corner.utils.CommonUtil;
import com.corner.utils.DialogUtil;
import com.corner.utils.LogUtil;
import com.corner.utils.NetUtil;
import com.corner.utils.SoftInputUtil;
import com.corner.utils.ToastUtil;
import com.corner.utils.view.InjectViewUtils;

import butterknife.ButterKnife;

/**
 * ============================================================
 * <p/>
 * 版权 ：Walker
 * <p/>
 * 作者：韩炜伟
 * <p/>
 * 版本 ：1.0
 * <p/>
 * 创建日期 ： 2015年4月8日上午10:40:29
 * <p/>
 * 描述 ： 所有的Activity都继承该类
 * <p/>
 * 修订历史 ：
 * <p/>
 * ============================================================
 */
public abstract class BaseActivity<P extends BasePresenter> extends FragmentActivity implements BaseView {
    protected P presenter;
    protected Dialog dialog;
    protected BroadcastReceiver netReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isConnected = NetUtil.checkNet(context);
            onNetStatusChanged(isConnected);
        }
    };

    protected abstract P createP();

    public void showProgressDialog() {
        if (dialog == null) {
            dialog = DialogUtil.showProgressDialog(this);
        } else {
            dialog.show();
        }
    }

    public void hideProgressDialog() {
        if (dialog != null) {
            DialogUtil.hideDialog(dialog);
        }
    }

    @Override
    protected void onCreate(android.os.Bundle arg0) {
        super.onCreate(arg0);
        presenter = createP();
        if (presenter != null) {
            presenter.setView(this);
        }
        registerBroadcast();
        setContentView();
        initView();
        setOnClick();
        initData();
        AppManager.getInstance().addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null) presenter.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (presenter != null) presenter.onPause();
    }

    protected abstract void setOnClick();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    public abstract void setContentView();

    public void initView() {
        ButterKnife.inject(this);
        InjectViewUtils.injectView(this);
    }

    /**
     * 网络状态改变
     *
     * @param isConnected
     */
    protected void onNetStatusChanged(boolean isConnected) {
    }

    /**
     * 注册网络判断的广播接收者
     */
    private void registerBroadcast() {
        IntentFilter netFilter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        netFilter.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(netReceiver, netFilter);
    }

    @Override
    protected void onDestroy() {
        if (presenter != null)
            presenter.onDestroy();
        presenter = null;
        hideProgressDialog();
        super.onDestroy();
        System.gc();
        unregisterReceiver(netReceiver);
        AppManager.getInstance().finishActivity(this);
    }

    /**
     * 跳转
     *
     * @param clazz
     */
    protected void jump(Class<? extends BaseActivity> clazz) {
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), clazz);
        startActivity(intent);
    }

    public void changeFragment(Fragment changeTofragment,
                               Fragment currentFragment, boolean isAddToStack) {
        if (currentFragment != null) {
            SoftInputUtil.hideSoftInput(currentFragment.getActivity(), ((BaseFragment) currentFragment).view);
        }
        if (this instanceof MutiFragment) {
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction()
                    .setCustomAnimations(R.anim.fragment_slide_in_right,
                            R.anim.fragment_slide_out_left,
                            R.anim.fragment_slide_in_left,
                            R.anim.fragment_slide_out_right)
                    .replace(((MutiFragment) this).getLayoutId(),
                            changeTofragment);
            if (isAddToStack) {
                transaction.addToBackStack(currentFragment.getClass()
                        .getSimpleName());
            }
            transaction.commit();
        }
    }

    public void popBackStack(String name) {
        getSupportFragmentManager().popBackStackImmediate(name,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
        LogUtil.e(getSupportFragmentManager().getBackStackEntryCount() + "");
    }

    /**
     * 在网络通畅的时候执行任务
     *
     * @param task
     */
    public void excuteTaskWhenNetOk(Task task) {
        if (NetUtil.checkNet(getApplicationContext())) {
            if (task != null) {
                task.onExcute();
            }
        } else {
            CommonUtil.showNetError(getApplicationContext());
        }
    }

    @Override
    public void showLoading(boolean isShow) {
        if (isShow) {
            showProgressDialog();
        } else {
            hideProgressDialog();
        }
    }

    @Override
    public void showError(String message) {
        ToastUtil.showCustomToastInDevelop(App.application, message);
    }

    public interface Task {
        void onExcute();
    }
}
